# _*_ coding: UTF-8 _*_
# @Time     : 2021/2/20 下午 02:57
# @Author   : Li Jie
# @Site     : http://www.hzdledu.com/
# @File     : prac1.py
# @Software : PyCharm

import socket

# 1. 获取以下域名对应的ip地址
'''
www.taobao.com
www.jd.com
www.baidu.com
www.hzdledu.com
输出为：
www.taobao.com的ip是xxx.xxx.xxx.xxx
...
'''


def prac1():
    hostnames = ['www.taobao.com', 'www.jd.com', 'www.baidu.com', 'www.hzdledu.com']
    hostips = []
    for hostname in hostnames:
        hostip = socket.gethostbyname(hostname)
        if hostip:
            hostips.append(hostip)
    for i in range(len(hostnames)):
        print(f'域名：{hostnames[i]:20}对应的ip：{hostips[i]}')


# 2.扫描并输出局域网占用的ip地址和对应计算机名
# 注意：单线程模式下耗时可能比较久


def prac2():
    start_ip = '172.16.20'
    exist_computer = []
    for i in range(1, 256):
        hostname = ''
        alias = ''
        addresslist = ''
        ip = f'{start_ip}.{i}'
        print(f'开始扫描ip:{ip}')
        try:
            (hostname, alias, addresslist) = socket.gethostbyaddr(ip)
        except:
            print(f'ip:{ip}未占用')
        else:
            exist_computer.append((hostname, addresslist))
            print(f'计算机名:{hostname}--->ip:{addresslist}')
        print('---------------------------------')


#3.利用socket实现一个简单的聊天室功能

if __name__ == '__main__':
    # prac1()
    prac2()
